<?php
require_once 'config.php';
/**
* DBHelper Class
*/
class DBHelper
{
    var $conn = null;

    /**
      * execSQL
      * execSQL("SELECT * FROM table WHERE id = ?", array('i', $id), false);
      * execSQL("SELECT * FROM table", array(), false);
      * execSQL("INSERT INTO table(id, name) VALUES (?,?)", array('ss', $id, $name), true);
      *
      * @author Ngo Quang Tinh
      * @access public
      * @param string $sql Statement to execute;
      * @param array $params array of type and values of the parameters (if any)
      * @param bool $close true to close $stmt (in inserts) false to return an array with the values;
      * @return multitype:unknown
     */
    function execSQL($sql, $params, $close){
        $mysqli = new mysqli(SERVER_HOST, SERVER_USER, SERVER_PW, SERVER_DB);
        $mysqli->set_charset("utf8");
        $stmt = $mysqli->prepare($sql) or die ("Failed to prepared the statement!");
        @call_user_func_array(array($stmt, 'bind_param'), $this->refValues($params));
        $stmt->execute();
        if($close){
            $result = $mysqli->affected_rows;
        } else {
            $meta = $stmt->result_metadata();

            while ( $field = $meta->fetch_field() ) {
                $parameters[] = &$row[$field->name];
            }

            call_user_func_array(array($stmt, 'bind_result'), $this->refValues($parameters));

            while ( $stmt->fetch() ) {
                $x = array();
                foreach( $row as $key => $val ) {
                    $x[$key] = $val;
                }
                $results[] = $x;
            }

            $result = $results;
        }

        $stmt->close();
        $mysqli->close();

        return  $result;
    }

    function refValues($arr){
        if (strnatcmp(phpversion(),'5.3') >= 0) //Reference is required for PHP 5.3+
        {
            $refs = array();
            foreach($arr as $key => $value)
                $refs[$key] = &$arr[$key];
            return $refs;
        }
        return $arr;
    }

    function holderInsert($param) {
        $holder = implode(',', array_fill(0, count($param)-1, '?'));
        return $holder;
    }
}
?>